// 建议引擎 - 处理评估结果对应的建议
import { getAssessResult } from './schema-loader.js'
import advices from "@/static/questionnaire/results/advice.json"

/**
 * 根据评估结果获取建议
 * @param {Object} assessmentResults - 评估结果对象
 * @returns {Object} 包含建议信息的对象
 */
export const getAdvicesFromAssessmentResults = (assessmentResults) => {
    if (!assessmentResults) return {};
    
    const advicesResult = {};
    
    for (const [key, result] of Object.entries(assessmentResults)) {
        if (!result) continue;
        
        const item = {
            title: result.title,
            iconUrl: result.iconUrl,
            advices: ""
        };
        
        // 处理建议 - 直接从解压结果中获取 aids
        const aids = result.advices || [];
        if (Array.isArray(aids) && aids.length > 0) {
            const uniqueAids = [...new Set(aids)]; // 去重
            let id = 1;
            for (const aid of uniqueAids) {
                const advice = advices[aid];
                if (advice == null) {
                    console.error(`未找到建议: ${aid}`);
                    continue;
                }
                for (const ad of advice) {
                    item.advices += id.toString() + ". " + ad + "\n";
                    id++;
                }
            }
        }
        
        advicesResult[key] = item;
    }
    
    return advicesResult;
}

/**
 * 建议引擎类
 */
export class AdviceEngine {
    constructor() {
        this.assessResultConfig = getAssessResult();
        this.advices = advices;
    }

    /**
     * 获取建议
     * @param {string} type - 问卷类型
     * @param {Object} results - 评估结果
     * @returns {Object} 建议信息
     */
    getAdvices(type, results) {
        if (type === 'assessment') {
            return getAdvicesFromAssessmentResults(results);
        }
        return {};
    }
}

// 创建全局实例
const adviceEngine = new AdviceEngine();

/**
 * 获取建议
 * @param {string} type - 问卷类型
 * @param {Object} results - 评估结果
 * @returns {Object} 建议信息
 */
export const getAdvices = (type, results) => adviceEngine.getAdvices(type, results);

export { adviceEngine };
